package cn.db101;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;

/**
 * @author zooy
 * @since 2024/6/5-10:58
 */
public class ButtonRound extends JButton {

    String text;
    Color backgroundColor;

    public ButtonRound(String s, Color c) {
        super(s);
        text = s;
        backgroundColor = c;
        this.setBorderPainted(false);
        this.setFocusPainted(false);
        this.setContentAreaFilled(false);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 设置并绘制背景颜色
        g.setColor(backgroundColor); // 浅青色
        Graphics2D g2 = (Graphics2D) g;
        RoundRectangle2D.Double rect = new RoundRectangle2D.Double(0, 0, (getWidth() - 3), (getHeight() - 3), 20, 20);
        g2.setColor(backgroundColor);
        g2.fill(rect);
        // 绘制文本
        // 设置文本属性
        g2.setColor(Color.BLACK); // 设置文本颜色
        g2.setFont(new Font("Arial", Font.PLAIN, 15)); // 设置文本字体和大小
        FontMetrics metrics = g2.getFontMetrics();
        int textWidth = metrics.stringWidth(text);
        int textHeight = metrics.getHeight();
        int x = (int) rect.getCenterX() - textWidth / 2;
        int y = (int) rect.getCenterY() + (textHeight / 2) - metrics.getDescent();
        g2.drawString(text, x, y);

        // 绘制圆角矩形边框（可选）
        g2.setColor(new Color(234,228,219));
        g2.draw(rect);

        if (getModel().isPressed()) {
            g.setColor(backgroundColor);
            g2.fillRect(3, 3, getWidth() - 6, getHeight() - 6);
        }
    }
}
